package ops.controller;

import java.util.HashMap;
import java.util.Map;

import ops.WindowManager;
import ops.model.Course;
import ops.model.EntityAlreadyExistsException;
import ops.model.Student;
import ops.model.manager.CourseManager;
import ops.model.manager.EntityController;
import ops.model.manager.StudentManager;
import ops.view.StudentRegisterPanel;

public class StudentController {
	
	private StudentManager studentManager;	
	
	private boolean adding;

	public StudentController() {
		studentManager = EntityController.getInstance().getStudentManager();
	}

	public void startAddProcess() {
		adding = true;
	}
	
	public void endAddProcess() {
		adding = false;
	}
	
	private void add(String name, int course, String email, int admission) {
		Long code = studentManager.nextLongID();
		
		Student student = new Student();
		student.setCode(code);
		student.setName(name);
		student.setCourse(course);
		student.setEmail(email);
		student.setAdmission(admission);
		
		try {
			studentManager.add(student);
			
			studentManager.save();
		} catch (EntityAlreadyExistsException e) {
			e.printStackTrace();
		}
	}
	
	private void edit(long code, String name, int course, String email, int admission) {
		Student student = studentManager.getObjectByKey(code);		
		student.setName(name);
		student.setCourse(course);
		student.setEmail(email);
		student.setAdmission(admission);
		
		studentManager.save();
	}
	
	public void saveStudent(long code, String name, int course, String email, int admission) {
		if (adding) {
			add(name, course, email, admission);
			
			adding = false;
		} else {
			edit(code, name, course, email, admission);
		}
		
		updateTable();
	}
	
	public void removeStudent(long code) {
		studentManager.remove(code);
		studentManager.save();
		
		updateTable();
	}
	
	public void updateTable() {
		StudentRegisterPanel panel = getPanel();
		
		panel.clearTable();
		
		for (Student student : studentManager.getMap().values()) {
			panel.addRowToTable(student.getCode(), student.getName(), 
					getCourseNameById(student.getCourse()), student.getEmail(), 
					ControllerManager.getInstance().getTermController().getTermNameById(student.getAdmission()));
		}
	}
	
	public String getCourseNameById(int code) { 
		CourseManager courseManager = EntityController.getInstance().getCourseManager();
		
		return courseManager.getObjectByKey(code).getName();
	}
	
	public Map<String, Object> getCoursesList() {
		CourseManager courseManager = EntityController.getInstance().getCourseManager();
		HashMap<String, Object> map = new HashMap<String, Object>();
		
		for (Course course: courseManager.getMap().values()) {
			map.put(course.getName(), course.getCode());
		}
		
		return map;
	}
	
	private StudentRegisterPanel getPanel() {
		return (StudentRegisterPanel) WindowManager.getInstance().getPanel("register.students");
	}
}
